package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取userId
        String userId = request.getHeader("userId");
        //如果userId存在，将用户信息放入到ThreadLocal中
        if (!StringUtils.isEmpty(userId)){
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            MediaThreadLocalUtil.set(user);
        }
        //最终都是放行，后面App端进行一些操作是不需要用户登陆的
        return true;
    }

    //后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放ThreadLocal中的数据，防止出现内存泄漏
        MediaThreadLocalUtil.remove();
    }
}
